import Icon from '@/components/Icon'
import useInitState from '@/hooks/useInitState'
import {
  getAllChannelsActionCreate,
  getUserChannelsActionCreate,
} from '@/store/actions/home'
import { RootAction, RootState } from '@/types/store'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleList from './ArticleList'
import Channels from './Channels'

import styles from './index.module.scss'

const Home = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 获取用户频道
  const { userChannels } = useInitState(getUserChannelsActionCreate).home
  // console.log('userChannels', userChannels)
  const [visible, setVisible] = useState(false)
  // 获取所有频道
  useInitState(getAllChannelsActionCreate)
  const activeId = useSelector((state: RootState) => state.home.activeId)

  // todo 一进入页面 获取userChannels第0项的id设置成activeId
  useEffect(() => {
    dispatch({
      type: 'home/set_active_id',
      payload: userChannels[0]?.id,
    } as RootAction)
  }, [dispatch, userChannels])

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        className="tabs"
        activeLineMode="fixed"
        activeKey={'' + activeId}
        onChange={(key) => {
          // 切换面板
          console.log(key)

          // 获取key同步到仓库中

          dispatch({
            type: 'home/set_active_id',
            payload: +key,
          } as RootAction)
        }}
      >
        {userChannels.map((item) => (
          <Tabs.Tab title={item.name} key={item.id}>
            {/* {item.name}的主体内容 */}
            <ArticleList channelId={item.id}></ArticleList>
          </Tabs.Tab>
        ))}
      </Tabs>

      <div className="tabs-opration">
        {/* 搜索功能 */}
        <Icon
          name="iconbtn_search"
          onClick={() => {
            console.log(' 点击了')
            history.push('/search')
          }}
        />
        {/* 频道设置 */}
        <Icon name="iconbtn_channel" onClick={() => setVisible(true)} />

        {/* 频道操作面板弹层 */}
        <Popup
          visible={visible}
          position="left"
          bodyStyle={{ width: '100vw' }}
          destroyOnClose
        >
          <Channels onClose={() => setVisible(false)}></Channels>
        </Popup>
      </div>
    </div>
  )
}

export default Home
